package com.platform.qujia.task;

import com.platform.qujia.constantEnum.RedisKey;
import com.platform.qujia.service.ISaleActivityOrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @date 2023/12/25
 */
@Component
public class SaleActivityOrderTask {

    private static final Logger log = LoggerFactory.getLogger(SaleActivityOrderTask.class);

    public static long ORDER_EXPIRE_TIME;

    @Autowired
    private ISaleActivityOrderService saleActivityOrderService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.profiles.active}")
    public void setOrderExpireTime(String profile){
        if (StringUtils.contains(profile,"prod")) {
            ORDER_EXPIRE_TIME = TimeUnit.MINUTES.toMillis(10);
        }else{
            ORDER_EXPIRE_TIME = TimeUnit.MINUTES.toMillis(3);
        }
    }

    @Scheduled(cron = "0 * * * * ?")
    public void scheduledCancelExpireOrder(){
        log.info("取消过期订单定时任务-开始");
        long pre = System.currentTimeMillis() - ORDER_EXPIRE_TIME;
        ZSetOperations<String, String> zSet = redisTemplate.opsForZSet();
        Set<String> orderNos = zSet.rangeByScore(RedisKey.SALE_ACTIVITY_ORDER_NOT_PAY, 0, pre);
        if (orderNos == null || orderNos.isEmpty()) {
            return;
        }
        for (String orderNo : orderNos) {
            Long removed = zSet.remove(RedisKey.SALE_ACTIVITY_ORDER_NOT_PAY, orderNo);
            if (removed!=null && removed>0) {
                saleActivityOrderService.cancelOrder(orderNo);
            }
        }
        log.info("取消过期订单定时任务-结束");
    }

}
